import type { Context } from 'koa';
import { SignupDto } from '@/dtos/signup.dto';
import { UserService } from '@/services/user';
import { pwdEncryption } from '@/helpers/encryption';
import { ResponseErrors } from '@/enums/responseErrors';

// 注册
export const signupController = async (ctx: Context) => {
  const input = ctx.request.body;
  const params = await ctx.vailParams<SignupDto>(SignupDto, input);

  const account = params.account;
  let password = params.password;

  const user = await UserService.findUserByAcnt(account);

  // 账户已存在
  if (user) {
    ctx.sendError(ResponseErrors.userExist);
    return;
  }

  // 密码加密
  password = pwdEncryption(password);

  //创建用户
  await UserService.createUser({ ...params, password });
  ctx.sendSuccess(null);
}